package cn.xxm.strategy.pay.i18n.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.util.List;
import java.util.Locale;


/**
 * 实现国际化配置文件定时刷新
 * @author XIEBO990
 */
@Component("fMessageSource")
@Slf4j
public class FMessageResourceExtension extends ReloadableResourceBundleMessageSource {


    @Value("${spring.messages.basename}")
    private String[] basenames;

    @Value("${spring.messages.encoding:UTF-8}")
    private String encoding;

    @Value("${spring.messages.cache-duration:-1M}")
    private String cache_duration;


    @PostConstruct
    public void init() {
        log.info("init MessageResourceExtension...");
        for (int i = 0; i < basenames.length; i++) {
            basenames[i] = "classpath:/" + basenames[i].replace('.', '/');
        }
        this.setBasenames(basenames);
        this.setDefaultEncoding(encoding);
        this.setCacheMillis(Duration.parse("PT"+cache_duration).toMillis());
        this.setFallbackToSystemLocale(false);

        //设置父MessageSource
        ReloadableResourceBundleMessageSource parent = new ReloadableResourceBundleMessageSource();
        parent.setBasename("message");
        this.setParentMessageSource(parent);
    }


    /**
     * 重写获取国际化文件方法
     *
     * @param code
     * @param locale
     * @return
     */
    @Override
    protected String resolveCodeWithoutArguments(String code, Locale locale) {
        if (getCacheMillis() < 0) {
            PropertiesHolder proHolder = getMergedProperties(locale);
            String result = proHolder.getProperty(code);
            if (result != null) {
                return result;
            }
        } else {
            String[] keys = code.split("\\.");
            code = keys[1];
            if (!StringUtils.isEmpty(keys[0])) {
                String basename = getBasenameSet().stream().filter(name -> StringUtils
                        .endsWithIgnoreCase(name, keys[0])).findFirst().orElse(null);
                if (!StringUtils.isEmpty(basename)) {
                    List<String> filenames = calculateAllFilenames(basename, locale);
                    System.out.println(filenames);
                    for (String filename : filenames) {
                        PropertiesHolder propHolder = getProperties(filename);
                        String result = propHolder.getProperty(code);
                        if (result != null) {
                            return result;
                        }
                    }
                }
            }
        }
        return null;
    }


}
